package org.wenhuayuan.uilibrary.banner.core;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class HiViewPager extends ViewPager {
    private int intervalTime; // 滚动的时间间隔
    private boolean isAutoPlay = true; // 是否自动滚滚动
    private boolean isLayout; // 表示是否有调用过onLayout
    private Handler handler = new Handler();
    private final static List<Handler> handerList = new ArrayList<>();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // 切换到下一个
            handler.postDelayed(this, intervalTime);
            next();
        }
    };

    public HiViewPager(@NonNull Context context) {
        super(context);
        init();
    }

    public HiViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    private void init() {
        Log.i("HiViewPager", "=====handler=init===="+handler);
        handerList.add(handler);
    }
    /** 开启自动播放 */
    public void setAutoPlay(boolean autoPlay) {
        this.isAutoPlay = autoPlay;
        Log.i("HiViewPager", "===========开启自动播放==========");
        if (!isAutoPlay) {
            handler.removeCallbacks(runnable);
        }
        start();
    }

    public void setIntervalTime(int intervalTime) {
        this.intervalTime = intervalTime;
    }

    /** 开始播放 */
    public void start() {
        Log.i("HiViewPager", "=====handler=start===="+handler);
        handler.removeCallbacksAndMessages(null);
        if (isAutoPlay) {
            handler.postDelayed(runnable, intervalTime);
        }

    }
    /** 停止自动播放  */
    public void stop() {
        Log.i("HiViewPager", "=====handler=stop===="+handler);
        Log.i("HiViewPager", "** 停止自动播放 ** ");
        for (Handler iHandler : handerList) {
            iHandler.removeCallbacksAndMessages(null);
        }
    }
    /** 设置下一个要显示的item，并返回pos  */
    private int  next() {
        int nextPosition = -1;
        if (getAdapter() == null || getAdapter().getCount() <= 1) {
            Log.i("HiViewPpager", "=====next()=====");
            stop();
            return nextPosition;
        }
        nextPosition = getCurrentItem() + 1;
        // 下一个索引大于最大数量时，重新开始
        if (nextPosition >= getAdapter().getCount()) {
            // 获取第一个item的索引
            nextPosition = ((HiBannerAdapter)getAdapter()).getFirstItem();
        }
        setCurrentItem(nextPosition, true);
        return nextPosition;
    }


    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        Log.i("HiViewPager", "====ev.getAction===="+ev.getAction());
        switch (ev.getAction()) {
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_POINTER_INDEX_MASK:
                start(); // 开始新一轮的播放，则需要清除消息队列中的任务
                break;
            default:
                Log.i("HiViewPager", "=====onTouchEvent stop()=====");
                stop();
                break;
        }


        return super.onTouchEvent(ev);
    }




    // viewpager + recyclerView
    // 当banner随着recyclerView滑上去后，会执行onDetachedFromWindow，这时viewpager会被回收。
    // 当再次滑出来时，会执行onAttachedToWindow然后出现一系列问题。滚动无动画+卡住
    // 通过下面方式解决

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        isLayout = true;
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (isLayout && getAdapter() != null && getAdapter().getCount() > 0) {
            try {
                // fix：反射设值，解决banner在recyclerView中，画上去、不见，然后再划出来时。没有动画~
                // 原因是在源码setCurrentItemInternal中
                Field field = ViewPager.class.getDeclaredField("mFirstLayout");
                field.setAccessible(true);
                field.set(this, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void setScrollDuration(int duration){
        try {
            Field scroller = ViewPager.class.getDeclaredField("mScroller");
            scroller.setAccessible(true);
            scroller.set(this, new HiBannerScroller(getContext(), duration));
        } catch (Exception e){}
    }

    @Override
    protected void onDetachedFromWindow() {
        // fix：解决banner在recyclerView中，画上去、不见，然后再划出来时。
        // 由于view被回收，导致终止了动画。图片卡住了
        if (((Activity)getContext()).isFinishing()) {
            stop();
            if(null != handerList) {
                for (int i = 0; i < handerList.size(); i++) {
                    handerList.remove(i);
                }
            }
            super.onDetachedFromWindow();
        }
        Log.i("HiViewPager", "=====onDetachedFromWindow stop()=====");
    }
}
